package com.cetcs.kmga.dataManager.controller;

import com.cetcs.kmga.common.*;
import com.cetcs.kmga.dataManager.annotation.LogAnnotation;
import com.cetcs.kmga.dataManager.entity.device.DeviceInfo;
import com.cetcs.kmga.dataManager.entity.device.DeviceLoginParams;
import com.cetcs.kmga.dataManager.entity.device.DeviceManufacturerIdentifier;
import com.cetcs.kmga.dataManager.entity.device.DeviceTypeIdentifier;
import com.cetcs.kmga.dataManager.entity.device.vi.DeviceIdVi;
import com.cetcs.kmga.dataManager.entity.device.vi.DeviceIdsVi;
import com.cetcs.kmga.dataManager.entity.device.vi.DeviceInfoVi;
import com.cetcs.kmga.dataManager.entity.device.vo.*;
import com.cetcs.kmga.dataManager.entity.global.LogLevelEnum;
import com.cetcs.kmga.dataManager.entity.global.LogTypeEnum;
import com.cetcs.kmga.dataManager.entity.global.NameAndValue;
import com.cetcs.kmga.dataManager.service.device.DeviceManagerService;
import com.cetcs.kmga.dataManager.util.Entity2Vo;
import com.cetcs.kmga.dataManager.util.Vi2DataMap;
import com.google.common.collect.Lists;
import deviceservice.token.AuthToken;
import deviceservice.utils.CryptoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * Created by XingWen on 2016/3/29.
 */

@RestController
@RequestMapping("/deviceManager")
public class DeviceManagerController extends BaseController {
    @Autowired
    private DeviceManagerService deviceManagerService;

    //获取所有的设备信息  分页
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "查看设备信息列表", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getAllDevicesByPages", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getAllDevicesByPages(WebRequest request,
                                             @RequestParam(required =false,defaultValue ="1")int page,
                                             @RequestParam(required =false,defaultValue ="5")int pageSize){
        try {
            Data data = getParam(request);
            Data params = new Data();
            params.put("page",page);
            params.put("pageSize",pageSize);
            //过滤参数
            if(data.getString("deviceType")!=null && !"-1".equals(data.getString("deviceType"))){
                params.put("type",data.getString("deviceType"));
            }
            if(data.getString("deviceState")!=null && !"-1".equals(data.getString("deviceState"))){
                params.put("status",data.getString("deviceState"));
            }
            if(data.getString("deviceText") != null && !"".equals(data.getString("deviceText"))){
                params.put("keyWords",data.getString("deviceText"));
                switch (data.getString("deviceName")){
                    case "设备名称":params.put("keyType","NAME");break;
                    case "设备编号":params.put("keyType","ID");break;
                    case "设备位置":params.put("keyType","LOCATION");break;
                    case "管理员":params.put("keyType","ADMIN_NAME");break;
                    default:throw new Exception("系统错误");
                }
            }
            Page pageResult = deviceManagerService.getDeviceInfosByPageAndCondition(params);
            List<DeviceInfoVo> deviceInfoVos = Lists.newArrayList();
            for(Object deviceInfo:pageResult.getContent()){
                deviceInfoVos.add(Entity2Vo.DeviceInfo2DeviceInfoVo((DeviceInfo) deviceInfo));
            }
            pageResult.setContent(deviceInfoVos);
            return this.ok(pageResult);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    //获取所有的设备信息 拓扑图
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "查看设备信息拓扑图", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getAllDevicesByType", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getDevicesTopologyByCondition(WebRequest request){
        try {
            Data data = getParam(request);
            Data params = new Data();
            //过滤参数
            if(data.getString("deviceType")!=null && !"-1".equals(data.getString("deviceType"))){
                params.put("type",data.getString("deviceType"));
            }
            if(data.getString("deviceState")!=null && !"-1".equals(data.getString("deviceState"))){
                params.put("status",data.getString("deviceState"));
            }
            if(data.getString("deviceText") != null && !"".equals(data.getString("deviceText"))){
                params.put("keyWords",data.getString("deviceText"));
                switch (data.getString("deviceName")){
                    case "设备名称":params.put("keyType","NAME");break;
                    case "设备编号":params.put("keyType","ID");break;
                    case "设备位置":params.put("keyType","LOCATION");break;
                    case "管理员":params.put("keyType","ADMIN_NAME");break;
                    default:throw new Exception("系统错误");
                }
            }
            TopologyVo topologyVo = deviceManagerService.getDevicesTopologyByCondition(params);
            return this.ok(topologyVo);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    //获取各种设备的数量 和状态
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "查看不同类型不同状态的设备数量", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getDeviceNumByType", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getDeviceNumByType(WebRequest request){
        try {
            Data data = getParam(request);
            //Page page = deviceManagerService.getDeviceInfosByCondition(data);
            Data params = new Data();
            //过滤参数
//            if(data.getString("deviceState")!=null && !"-1".equals(data.getString("deviceState"))){
//                params.put("status",data.getString("deviceState"));
//            }else{
//                params.put("status",2);
//            }
//            if(data.getString("deviceText") != null && !"".equals(data.getString("deviceText"))){
//                params.put("keyWords",data.getString("deviceText"));
//                switch (data.getString("deviceName")){
//                    case "设备名称":params.put("keyType","NAME");break;
//                    case "设备编号":params.put("keyType","ID");break;
//                    case "设备位置":params.put("keyType","LOCATION");break;
//                    case "管理员":params.put("keyType","ADMIN_NAME");break;
//                    default:throw new Exception("系统错误");
//                }
//            }
            //params.put("status",2);
            DeviceSummaryQuantityVo deviceSummaryQuantityVo = new DeviceSummaryQuantityVo();
            deviceSummaryQuantityVo = deviceManagerService.getDeviceNumByType(params);
            return this.ok(deviceSummaryQuantityVo);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    //更新设备
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "更新设备信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/updateDevice/{id}", method = RequestMethod.PUT, produces = {"application/json", "application/xml"})
    public BaseResponse updateDevice(WebRequest request,@PathVariable("id")String id, @Valid @RequestBody DeviceInfoVi deviceInfoVi, BindingResult bindingResult){
        try {
            //Data data = getParam(request);
            Data params = Vi2DataMap.DeviceInfoVi2DataMap(deviceInfoVi);
            if(deviceInfoVi.getDevice_name()!=null){
                Data dataMap  = new Data();
                dataMap.put("name",deviceInfoVi.getDevice_name());
                dataMap.put("idF",deviceInfoVi.getId());
                //判断 设备是否存在
                Integer isRepeat = 0;
                isRepeat = deviceManagerService.isExistDevice(dataMap);
                if(isRepeat>0){
                    return this.error(Constant.SYSTEM_EXCEPTION,"设备名称已存在！请换用其他名称");
                }
            }
            params.put("id",id);
            Integer result = deviceManagerService.updateDeviceInfo(params);
            return this.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }



    //添加设备
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "添加新设备", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/addDevice", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse addDevice(WebRequest request, @Valid @RequestBody DeviceInfoVi deviceInfoVi, BindingResult bindingResult){
        try {
            //Data data = getParam(request);
            Data params = Vi2DataMap.DeviceInfoVi2DataMap(deviceInfoVi);
            if(deviceInfoVi.getDevice_name()!=null){
                Data dataMap  = new Data();
                dataMap.put("name",deviceInfoVi.getDevice_name());
                //判断 设备是否存在
                Integer isRepeat = 0;
                isRepeat = deviceManagerService.isExistDevice(dataMap);
                if(isRepeat>0){
                    return this.error(Constant.SYSTEM_EXCEPTION,"设备名称已存在！请换用其他名称");
                }
            }
            //params.put("id",deviceInfoVi.getDevice_ip()+new Date().getTime());
            Integer result = deviceManagerService.createDeviceInfo(params);
            if(result > 0) {
                return this.ok(result);
            }else {
                return this.error(Constant.SYSTEM_EXCEPTION,"设备添加失败!请检查设备参数是否正确!");
            }
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 删除设备
     * @param request
     * @param deviceIdVi
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "删除设备", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/deleteDevice", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse deleteDevice(WebRequest request,@Valid  @RequestBody DeviceIdVi deviceIdVi, BindingResult bindingResult){
        try {
            //Data data = getParam(request);
            Data params = new Data();
            params.put("id",deviceIdVi.getId());
            DeviceInfo deviceInfo = deviceManagerService.getDeviceInfoById(params);
            if(!"2".equals(deviceInfo.getStatus())){
                return this.error(Constant.SYSTEM_EXCEPTION,"设备" + deviceInfo.getName() + "不是正常状态，请检查设备");
            }
            Integer result = deviceManagerService.deleteDeviceInfo(params);
            return this.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION,e.getMessage());
        }
    }


    /**
     * 删除设备
     * @param request
     * @param deviceIdsVi
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "批量删除设备", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/batchDeleteDevice", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse batchDeleteDevice(WebRequest request,@Valid  @RequestBody DeviceIdsVi deviceIdsVi, BindingResult bindingResult){
        try {
            //Data data = getParam(request);
            Data params = new Data();
            params.put("ids",deviceIdsVi.getId());
            Integer result = deviceManagerService.batchDeleteDevice(params);
            return this.ok(result);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 获取设备口令
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "获取设备口令", logLevel = LogLevelEnum.中)
    @RequestMapping(value = "/getDeviceSecretById/{id}", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getAllSecret(@PathVariable("id")String id){
        try {
            Data params = new Data();
            params.put("id",id);
            params.put("timestamp",new Date().getTime());
            DeviceInfo deviceInfo = deviceManagerService.getDeviceInfoById(params);
            DeviceTokenVo deviceTokenVo = new DeviceTokenVo();
            deviceTokenVo.setId(deviceInfo.getId());
            String newToken = AuthToken.getLoginToken(deviceInfo.getToken(), (Long) params.get("timestamp"),deviceInfo.getId());
            deviceTokenVo.setToken(newToken);
            deviceTokenVo.setTimestamp(String.valueOf(params.get("timestamp")));
            return this.ok(deviceTokenVo);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }



    /**
     * 获取设备类型
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "获取设备类型", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getAllDeviceType", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getAllDeviceType(){
        try {
            Data params = new Data();
            List<DeviceTypeIdentifier> deviceTypeIdentifiers = deviceManagerService.getAllDeviceType(params);
            List<KeyAndValueVo> keyAndValueVos = Lists.newArrayList();
            for(DeviceTypeIdentifier deviceTypeIdentifier:deviceTypeIdentifiers){
                keyAndValueVos.add(Entity2Vo.DeviceType2KeyAndValueVo(deviceTypeIdentifier));
            }
            return this.ok(keyAndValueVos);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 获取设备厂商类型
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "获取设备厂商类型", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getAllDeviceManufacturer", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getAllDeviceManufacturer(){
        try {
            Data params = new Data();
            List<DeviceManufacturerIdentifier> deviceManufacturerIdentifiers = deviceManagerService.getAllDeviceManufacturer(params);
            List<KeyAndValueVo> keyAndValueVos = Lists.newArrayList();
            for(DeviceManufacturerIdentifier deviceManufacturerIdentifier:deviceManufacturerIdentifiers){
                keyAndValueVos.add(Entity2Vo.DeviceManufacturerIdentifier2KeyAndValueVo(deviceManufacturerIdentifier));
            }
            return this.ok(keyAndValueVos);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }





    /**
     * 获取设备状态信息--折线图
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "获取某一设备状态信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getDeviceStatusInfoById/{id}", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getDeviceStatusInfoById(@PathVariable("id")String id,
                                                @RequestParam(required =false,defaultValue ="0")String time){
        try {
            Data params = new Data();
            params.put("id",id);
            params.put("type",time);
            DeviceStatusInfoVo deviceStatusInfoVo = deviceManagerService.getDeviceStatusInfoById(params);
            return this.ok(deviceStatusInfoVo);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 获取设备配置接口菜单
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "获取某一设备配置接口菜单", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getDeviceConfigMenuById/{id}", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getDeviceConfigMenuById(@PathVariable("id")String id){
        try {
            Data params = new Data();
            params.put("id",id);
            List<DeviceConfigMenuVo> deviceConfigMenuVos = deviceManagerService.getDeviceConfigMenuById(params);
            return this.ok(deviceConfigMenuVos);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }



    /**
     * 获取设备登录跳转接口
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "设备管理", logType = LogTypeEnum.业务日志, description = "获取设备登录跳转接口", logLevel = LogLevelEnum.中)
    @RequestMapping(value = "/getLoginParamsByDevId/{id}", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getLoginParamsByDevId(@PathVariable("id")String id){
        try {
            Data params = new Data();
            params.put("id",id);
            DeviceInfo deviceInfo = deviceManagerService.getDeviceInfoById(params);
            //封装设备的登录信息
            params.clear();
            params.put("deviceType",deviceInfo.getType());
            List<DeviceLoginParams> deviceLoginParams = deviceManagerService.getDeviceLoginParamsByDeviceID(params);
            DeviceLoginParamsVo deviceLoginParamsVo = new DeviceLoginParamsVo();
            if("探针设备".equals(deviceInfo.getType().trim())){
                deviceLoginParamsVo.setType(1);
            }else if("脱敏设备".equals(deviceInfo.getType().trim())){
                deviceLoginParamsVo.setType(2);
            }else if("运维设备".equals(deviceInfo.getType().trim())){
                deviceLoginParamsVo.setType(2);
            }
            if(deviceLoginParams.size()>0){
                deviceLoginParamsVo.setAction(deviceLoginParams.get(0).getLoginUrl().replace("localhost",deviceInfo.getIp()));
                List<NameAndValue> nameAndValues = Lists.newArrayList();
                NameAndValue nameAndValue1 = new NameAndValue();
                nameAndValue1.setName(deviceLoginParams.get(0).getUserName());
                nameAndValue1.setValue(deviceInfo.getUsr());
                nameAndValues.add(nameAndValue1);
                NameAndValue nameAndValue2 = new NameAndValue();
                nameAndValue2.setName(deviceLoginParams.get(0).getPassword());
                if("探针设备".equals(deviceInfo.getType().trim())){
                    nameAndValue2.setValue(CryptoUtil.aesDecrypt(deviceInfo.getPassword(),CryptoUtil.hash(deviceInfo.getId())));
                }else if("脱敏设备".equals(deviceInfo.getType().trim())){
                    nameAndValue2.setValue(CryptoUtil.aesDecrypt(deviceInfo.getPassword(),CryptoUtil.hash(deviceInfo.getId())));
                }else if("运维设备".equals(deviceInfo.getType().trim())){
                    nameAndValue2.setValue(deviceInfo.getPassword());
                }
                nameAndValues.add(nameAndValue2);
                deviceLoginParamsVo.setContent(nameAndValues);
            }else {
                deviceLoginParamsVo.setAction("http://" + deviceInfo.getIp() + "/index.html");
                List<NameAndValue> nameAndValues = Lists.newArrayList();
                NameAndValue nameAndValue1 = new NameAndValue();
                nameAndValue1.setName("userName");
                nameAndValue1.setValue(deviceInfo.getUsr());
                nameAndValues.add(nameAndValue1);
                NameAndValue nameAndValue2 = new NameAndValue();
                nameAndValue2.setName("password");
                if("探针设备".equals(deviceInfo.getType().trim())){
                    nameAndValue2.setValue(CryptoUtil.aesDecrypt(deviceInfo.getPassword(),deviceInfo.getId()));
                }else if("脱敏设备".equals(deviceInfo.getType().trim())){
                    nameAndValue2.setValue(CryptoUtil.aesDecrypt(deviceInfo.getPassword(),deviceInfo.getId()));
                }else if("运维设备".equals(deviceInfo.getType().trim())){
                    nameAndValue2.setValue(deviceInfo.getPassword());
                }
                nameAndValues.add(nameAndValue2);
                deviceLoginParamsVo.setContent(nameAndValues);
            }
            return this.ok(deviceLoginParamsVo);
        }catch (Exception e){
            e.printStackTrace();
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }



}
